package chagine.mdt.config;

import chagine.core.current.CurrentEnv;
import chagine.core.current.RequestContent;
import com.baomidou.mybatisplus.core.handlers.MetaObjectHandler;
import lombok.extern.slf4j.Slf4j;
import org.apache.ibatis.reflection.MetaObject;
import org.springframework.stereotype.Component;

import java.time.LocalDateTime;

@Slf4j
@Component
public class ChagineMetaObjectHandler implements MetaObjectHandler {

    @Override
    public void insertFill(MetaObject metaObject) {

        LocalDateTime currentTime = LocalDateTime.now();
        RequestContent content = CurrentEnv.getContent();
        Long userId = content.getUser();
        Long tenantId = content.getTenant();

        // 用户信息
        if (userId != null) {
            this.strictInsertFill(metaObject, "createUser", String.class, userId.toString()); // 起始版本 3.3.3(推荐)
            this.strictInsertFill(metaObject, "chanUser", String.class, userId.toString()); // 起始版本 3.3.3(推荐)
        }
        // 时间(秒)
        this.strictInsertFill(metaObject, "createTime", LocalDateTime.class, currentTime); // 起始版本 3.3.3(推荐)
        this.strictInsertFill(metaObject, "chanTime", LocalDateTime.class, currentTime); // 起始版本 3.3.3(推荐)
        // 租户信息，当前租户
        if (tenantId != null) {
            this.strictInsertFill(metaObject, "tenaId", String.class, tenantId.toString()); // 起始版本 3.3.3(推荐)
        }
        // 变更引起的请求
        this.strictInsertFill(metaObject, "chanRequest", Long.class, content.getId()); // 起始版本 3.3.3(推荐)
    }

    @Override
    public void updateFill(MetaObject metaObject) {

        RequestContent content = CurrentEnv.getContent();
        Long userId = content.getUser();
        if (userId != null) {
            this.strictUpdateFill(metaObject, "chanUser", String.class, userId.toString()); // 起始版本 3.3.3(推荐)
        }

        // 时间(秒)
        this.strictUpdateFill(metaObject, "chanTime", LocalDateTime.class, LocalDateTime.now()); // 起始版本 3.3.3(推荐)
        // 变更引起的请求
        this.strictUpdateFill(metaObject, "chanRequest", Long.class, content.getId()); // 起始版本 3.3.3(推荐)
    }
}

